import socket 
import pyaudio 

CHUNK = 1024
FORMAT = pyaudio.paInt16 
CHANNELS = 1
RATE = 16000


p = pyaudio.PyAudio()
# 捕获麦克风
stream = p.open(format=FORMAT,  channels=CHANNELS, rate=RATE, input=True,input_device_index=1, frames_per_buffer=CHUNK)
# 捕获系统本地音频
stream2 = p.open(format=FORMAT,  channels=CHANNELS, rate=RATE, input=True,input_device_index=2, frames_per_buffer=CHUNK)

sender_socket = socket.socket(socket.AF_INET,  socket.SOCK_STREAM)
sender_socket.connect(('localhost', 12345))  # 替换为接收端地址 

try:
    while True:
        data = stream.read(CHUNK) 
        sender_socket.sendall(data) 
        data2 = stream2.read(CHUNK) 
        sender_socket.sendall(data2) 
        print("发送")
except KeyboardInterrupt:  # Ctrl+C触发 
    print("\n用户请求断开连接")
    sender_socket.sendall(b"!DISCONNECT")   # 自定义断开协议头 
    # 客户端接收
    length = int.from_bytes(sender_socket.recv(4),  'big')
    result_data = sender_socket.recv(length) 
    # result_data = sender_socket.recv(4096) 
    print(f"收到识别结果: {result_data.decode('utf-8')}") 
    sender_socket.close() 
    stream.stop_stream() 
    stream2.stop_stream() 
    p.terminate()
    